package com.yklx.youke.admin.controller;

import com.yklx.youke.entity.Permission;
import com.yklx.youke.admin.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@RestController
@RequestMapping("/api/admin/permissions")
@CrossOrigin(origins = "*")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;

    @GetMapping
    @PreAuthorize("hasAuthority('permission:read')")
    public ResponseEntity<List<Permission>> getAllPermissions() {
        try {
            List<Permission> permissions = permissionService.getAllPermissions();
            return ResponseEntity.ok(permissions);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("error", "Failed to load permissions: " + e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:read')")
    public ResponseEntity<Permission> getPermissionById(@PathVariable String id) {
        try {
            Permission permission = permissionService.getPermissionById(id);
            if (permission != null) {
                return ResponseEntity.ok(permission);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping
    @PreAuthorize("hasAuthority('permission:write')")
    public ResponseEntity<?> createPermission(@RequestBody Permission permission) {
        try {
            boolean success = permissionService.createPermission(permission);
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "Permission created successfully");
                response.put("permission", permission);
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(Map.of("error", "Failed to create permission"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(Map.of("error", "Failed to create permission: " + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:write')")
    public ResponseEntity<?> updatePermission(@PathVariable String id, @RequestBody Permission permission) {
        try {
            permission.setPermissionId(id);
            boolean success = permissionService.updatePermission(permission);
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "Permission updated successfully");
                response.put("permission", permission);
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(Map.of("error", "Failed to update permission"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(Map.of("error", "Failed to update permission: " + e.getMessage()));
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('permission:write')")
    public ResponseEntity<?> deletePermission(@PathVariable String id) {
        try {
            boolean success = permissionService.deletePermission(id);
            if (success) {
                Map<String, Object> response = new HashMap<>();
                response.put("message", "Permission deleted successfully");
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body(Map.of("error", "Failed to delete permission"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().body(Map.of("error", "Failed to delete permission: " + e.getMessage()));
        }
    }
}